package com.fadadianqi.logistics.admin.net.mina;

import com.fadadianqi.logistics.admin.net.Connection;
import com.fadadianqi.logistics.admin.net.Packet;
import org.apache.commons.logging.Log;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import java.io.UnsupportedEncodingException;

/**
 * @author aroot
 */
public class NIOConnection implements Connection {

    private static final Log LOG = org.apache.commons.logging.LogFactory.getLog(NIOConnection.class);


    private IoSession ioSession;
    private boolean closedFlag = false;

    public NIOConnection(IoSession ioSession) {
        this.ioSession = ioSession;
    }

    @Override
    public boolean isClosed() {
        return closedFlag;
    }

    @Override
    public boolean isAvaliable() {
        return ioSession.isConnected();
    }

    @Override
    public void close() {
        synchronized (this) {
            ioSession.close(true);
        }
        closedFlag = true;
    }

    private static final String CHARTSET = "UTF-8";

    @Override
    public void deliver(String text) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("#deliver#, text: " + text);
        }
        IoBuffer buffer = IoBuffer.allocate(text.length());
        buffer.setAutoExpand(true);
        try {
            buffer.put(text.getBytes(CHARTSET));
            buffer.flip();
            ioSession.write(buffer);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            LOG.error(e);
            close();
        }
    }

    @Override
    public void deliver(Packet packet) {
        if (packet == null || packet.toBytes().length == 0) {
            LOG.warn("#deliver#, packet == null || packet.toBytes().length == 0");
            return;
        } else if (!ioSession.isConnected()) {
            LOG.warn("#deliver#, !ioSession.isConnected()");
            return;
        }
        byte[] bytes = packet.toBytes();
        IoBuffer buffer = IoBuffer.allocate(bytes.length, true);
        buffer.put(bytes);
        buffer.flip();
        //WriteFuture wf = ioSession.write(buffer);
        ioSession.write(buffer);
    }

}
